package com.example.springbootdockerdemo.exception;

import com.example.springbootdockerdemo.entity.ErrorInfo;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

/**
 * @ClassName GlobalExceptionHandler
 * @Author Chengy
 * @Date 2021/11/22 15:14
 * @Version 1.0
 */

@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ErrorInfo<Exception> jsonApiErrorHandler(HttpServletRequest request, Exception e) {
        ErrorInfo<Exception> errorInfo = new ErrorInfo<>();
        try {
            System.out.println("统一异常处理");
            e.printStackTrace();

            Throwable innerEx = e.getCause();
            while (innerEx != null) {
                if (innerEx.getCause() == null) {
                    break;
                }
                innerEx = innerEx.getCause();
            }

            if (innerEx == null) {
                errorInfo.setMessage(e.getMessage());
                errorInfo.setError(e.toString());
            } else {
                errorInfo.setMessage(e.getMessage());
                errorInfo.setError(e.toString());
            }


            errorInfo.setData(e);
            errorInfo.setTimestamp(System.currentTimeMillis());
            errorInfo.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());//500错误
            errorInfo.setUrl(request.getRequestURL().toString());
            errorInfo.setPath(request.getServletPath());

        } catch (Exception ex) {
            ex.printStackTrace();
            errorInfo.setMessage(ex.getMessage());
            errorInfo.setError(ex.toString());
        }

        return errorInfo;
    }


}
